package com.hycreate.platform.modules.element;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hycreate.platform.common.config.Config;
import com.hycreate.platform.common.config.Global;
import com.hycreate.platform.common.persistence.Page;
import com.hycreate.platform.common.utils.FileUtils;
import com.hycreate.platform.common.utils.StringUtils;
import com.hycreate.platform.common.utils.excel.ImportExcel;
import com.hycreate.platform.common.utils.mypage.PageDemo;
import com.hycreate.platform.common.utils.mypage.PageDemoUtil;
import com.hycreate.platform.common.web.BaseController;
import com.hycreate.platform.modules.atta.SfAttachment;
import com.hycreate.platform.modules.atta.SfAttachmentService;
import com.hycreate.platform.modules.product.SfProduct;
import com.hycreate.platform.modules.product.element.SfProductElement;
import com.hycreate.platform.modules.project.SfProject;
import com.hycreate.platform.modules.project.SfProjectImport;
import com.hycreate.platform.modules.project.product.SfProjectProduct;
import com.hycreate.platform.modules.sys.utils.UserUtils;

/**
 * 配件Controller
 * @author hoader
 * @version 2017-01-09
 */
@Controller
@RequestMapping(value = "${adminPath}/element/sfElement")
public class SfElementController extends BaseController {

	@Autowired
	private SfElementService sfElementService;
	
	@Autowired
	private SfAttachmentService sfAttachmentService;
	
	@ModelAttribute
	public SfElement get(@RequestParam(required=false) String id) {
		SfElement entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sfElementService.get(id);
		}
		if (entity == null){
			entity = new SfElement();
		}
		return entity;
	}
	
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = {"list", ""})
	public String list(SfElement sfElement, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SfElement> page = sfElementService.findPage(new Page<SfElement>(request, response), sfElement); 
		model.addAttribute("page", page);
		return "modules/element/sfElementList";
	}

	
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "productelementlist")
	public String productelementlist(SfElement sfElement, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		    int everyPage=30; //每页30条
			int current=0;
		    String temp=request.getParameter("current");
			if(temp!=null){
				 current=Integer.parseInt(temp);
			} 
			 String type= request.getParameter("type");
		
		     String pid=request.getParameter("pid");
		     
		     System.out.println("---------------pid----"+pid);
		

			 int total= sfElementService.elementCount(pid);
			 int totalPages=PageDemoUtil.Comparison(total,everyPage); //总页数
			 PageDemo pd=PageDemoUtil.Calculation(total, current, type,everyPage);
			 
		
			 pd.setValueId(pid);
			    
			 List<SfElement> list= sfElementService.findElement(pd);
			 
			 System.out.println("---------"+list.size());
			// 把数据传回前台
			model = Paging(model, current, total, type, everyPage);
	
            model.addAttribute("list", list);
         
            model.addAttribute("tp", totalPages);
		
            model.addAttribute("pid", pid);
		
		return "modules/element/ProductElementList";
	}
	
	
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "form")
	public String form(SfElement sfElement, Model model) {
		model.addAttribute("sfElement", sfElement);
		return "modules/element/sfElementForm";
	}

	@RequiresPermissions("element:sfElement:edit")
	@RequestMapping(value = "save")
	public String save(SfElement sfElement, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sfElement)){
			return form(sfElement, model);
		}
		sfElementService.save(sfElement);
		addMessage(redirectAttributes, "保存配件成功");
		return "redirect:"+Global.getAdminPath()+"/element/sfElement/?repage";
	}
	
	@RequiresPermissions("element:sfElement:edit")
	@RequestMapping(value = "delete")
	public String delete(SfElement sfElement, RedirectAttributes redirectAttributes) {
		
		 List<String> delList = new ArrayList<String>();
		 
		 delList.add(sfElement.getId());
		
		sfElementService.delete(sfElement);
		
		sfElementService.DeletesRedundancy(delList);
		
		addMessage(redirectAttributes, "删除配件成功");
		return "redirect:"+Global.getAdminPath()+"/element/sfElement/?repage";
	}

	/**
	 * 导入备件图片数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("element:sfElement:edit")
    @RequestMapping(value = "importPic", method=RequestMethod.POST)
    public String importPic(MultipartFile mfile, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		
		/**
		 * 文件存储路径
		 */
		StringBuffer unZipCopyPath = new StringBuffer(request.getSession().getServletContext().getRealPath("/"));
		unZipCopyPath.append("userfiles/").append(UserUtils.getUser().getId()).append("/element/images/").append("XXX");
		
		/**
		 * 文件访问路径
		 */
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append(request.getContextPath());
		urlBuffer.append("/userfiles/").append(UserUtils.getUser().getId()).append("/element/images/");
		
		int successNum = 0;//成功数
		int failureNum = 0;//失败数
		
		StringBuilder failureMsg = new StringBuilder();
		String descDir = Config.getConfig("unZip.element.pic");
		FileUtils.createDirectory(descDir);
		String upFilePath = descDir + "/" + mfile.getOriginalFilename();
		try {
			mfile.transferTo(new File(upFilePath));
			
			this.unZip(descDir + "/", upFilePath);
			
			String unzipPath = descDir + "/" + mfile.getOriginalFilename().split("\\.")[0];
			File descDirFile = new File(unzipPath);
			String[] fileNames = descDirFile.list();//
			FilenameFilter filter=new FilenameFilter() {  
	            @Override  
	            public boolean accept(File dir, String name) {
	            	name = name.toLowerCase();
	                return name.endsWith(".jpg") || name.endsWith(".png");  
	            }  
	        };
			
	        SfElement sfElement;
			SfAttachment sfAttachment;
			List<SfElement> sfElemnetList = null;
			for(String fileName : fileNames){
				if (fileName.split("\\.").length < 1) {
					continue;
				}
				
				/*String []  elePic=fileName.split("\\.");*/
				
		        String pic=fileName.substring(0,fileName.lastIndexOf("."));
				
				sfElement = new SfElement();
				sfElement.setCode(pic);
				sfElemnetList = sfElementService.findList(sfElement);
				if(CollectionUtils.isEmpty(sfElemnetList)){
					failureMsg.append("<br/>备件编号"+fileName+"不存在！; ");
					failureNum++;
					continue;
				}
				sfElement = sfElemnetList.get(0);
				File descDirPicFile = new File(unzipPath+ "/" + fileName);
				/*File[] picFiles = descDirPicFile.listFiles(filter);*/
				
					FileUtils.copyFile(descDirPicFile.getAbsolutePath(), unZipCopyPath.toString().replace("XXX", fileName));
					sfAttachment = new SfAttachment();
					sfAttachment.setObjectId(sfElement.getId());
					sfAttachment.setUrl(urlBuffer.toString() + descDirPicFile.getName());
					sfAttachmentService.save(sfAttachment);
					
					sfElement.setExistImage("已有");
					sfElementService.save(sfElement);
				
				successNum++;
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条备件，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条备件"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		FileUtils.deleteDirectory(descDir);
		return "redirect:" + adminPath + "/element/sfElement/list?repage";
	}
	
	
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "batchDeletes")
	public void batchDeletes( HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		List<String> delList = batch_deletion(request);

		try {
			sfElementService.batchDeletes(delList);
			
			sfElementService.DeletesRedundancy(delList);
		} catch (Exception e) {
			logger.error("删除失败");

		}
		
		
		
	}
	
	/**
	 * 删除产品配件表中的冗余数据
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "deletesAssociation")
	public String  deletesAssociation( HttpServletRequest request,
			HttpServletResponse response, Model model) {
	  
	   List<String> delList = new ArrayList<String>();
		
	   List<SfProductElement>  list=sfElementService.DELLIST();
		
	    System.out.println(list.size()); 
	    
	    for (SfProductElement sfProductElement : list) {
			
	    	delList.add(sfProductElement.getId());
		}
	    
	    
		
	    try {
			sfElementService.DeletesRedundancy(delList);
		} catch (Exception e) {
			
			logger.error("删除失败");
		}
		
		return "modules/element/ProductElementList";
	}
	
	
	
	@RequiresPermissions("element:sfElement:view")
	@RequestMapping(value = "updateelementimport", method = RequestMethod.POST)
	public String importProjectFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<UpdateElementImport> list = ei.getDataList(UpdateElementImport.class);

			SfElement sfElement = null;
			List<SfElement> sfElementList = null;
			int i = 0;

			for (UpdateElementImport updateElement : list) {
				try {
					boolean isFlag = false;

					/**
					 * 项目编号为空，为无效数据
					 */
					if (StringUtils.isEmpty(updateElement.getElementCode()
							.trim())) {
						failureMsg.append("<br/>项目编号为空，为无效数据; ");
						continue;
					}

					
					sfElement=new SfElement();
					
					sfElement.setCode(updateElement.getElementCode().trim());
					
					sfElementList=sfElementService.findList(sfElement);
					
					if (CollectionUtils.isEmpty(sfElementList)) {
						
						failureMsg.append("<br/>配件编号不存在，为无效数据; ");
						continue;
					}else{
						
						if(sfElementList.size()==1){
							
							sfElement=	sfElementList.get(0);
							
							sfElement.setNum(updateElement.getNowNumber().trim());
							sfElement.setSafeNum(updateElement.getSafeNumber().trim());
							sfElement.setWarehouse(updateElement.getWarehouse().trim());
							
							sfElementService.save(sfElement);
							
							isFlag=true;
						}
						
						
					}

					

					if (isFlag) {
						successNum++;
					} else {
						failureMsg.append("<br/>无效数据; " + i);
					}
					

				} catch (Exception e) {
					e.printStackTrace();
					failureNum++;
				}
				i++;
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条项目，导入信息如下：");
			}
			addMessage(redirectAttributes, "已更新 " + successNum + " 条数据"
					+ failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "更新数据失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/element/sfElement/list?repage";
	}
	
	
	
	
	
	
	
	@SuppressWarnings("rawtypes")
	private void unZip(String descDir, String upFilePath) throws IOException {
		ZipFile zip = new ZipFile(upFilePath, "GBK");
		for (Enumeration entries = zip.getEntries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			logger.debug(outPath);

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		logger.debug("******************解压完毕********************");
	}
	
	/**
	 * 
	 * batch_deletion:(批量删除，把前台的字符串截取为list对象)
	 * 
	 * @param request
	 * @return 返回删除的集合
	 */
	private List<String> batch_deletion(HttpServletRequest request) {
		String items = request.getParameter("delitems");

		List<String> delList = new ArrayList<String>();
		String[] strs = items.split(",");
		for (String str : strs) {
			delList.add(str);
		}
		return delList;
	}
	
	// 返回的页数的方法
			private Model Paging(Model model, int current, int total, String type,
					int everyPage) {
				if(type==null){
					return model.addAttribute("current", 1);	
				}
				
				if (type.equals("hasPrePage")) {

					if (current > 1) {
						return model.addAttribute("current", current);
					} else {
						return model.addAttribute("current", 1);
					}

				} else if (type.equals("hasNextPage")) {
					if (current < PageDemoUtil.Comparison(total, everyPage)) {
						return model.addAttribute("current", current);
					} else {
						return model.addAttribute("current",
								PageDemoUtil.Comparison(total, everyPage));
					}
				} else if (type.equals("startPage")) {
					
					return model.addAttribute("current", 1);
				} else if (type.equals("endPage")) {
					return model.addAttribute("current",
							PageDemoUtil.Comparison(total, everyPage));
				} else if (type.equals("pagenumb")) {

					return model.addAttribute("current", current);
				} else {

					return model;
				}

			}
	
}